package myHashBuck;

public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小


    public HashBucket() {
        // write code here
        array = new Node[16];
    }

    public void put(int key, int value) {
        // write code here
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {  //先搜索一下，如果有相同的Key值，那就修改value值
            if (cur.key == key) {
                cur.value = value; //覆盖当前值
                return;  //返回
            }
            cur = cur.next;
        }

        Node newNode = new Node(key, value); //新建立节点
        newNode.next = array[index];
        array[index] = newNode;
        size++;

        if (this.loadFactor() >= 0.75) {  //如果负载因子 > 0.75，那就要重新调整哈希桶大小
            this.resize();
        }
    }


    private void resize() {
        // write code here
        Node[] newArr = new Node[array.length * 2]; //重新申请数组
        //需要重新哈希
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                int index = cur.key % newArr.length; //当前Key在新数组的位置
                Node curNext = cur.next; //记录下一个节点的位置
                cur.next = newArr[index];
                newArr[index] = cur;
                cur = curNext;
            }
        }
        array = newArr;
    }


    private double loadFactor() {  //计算负载因子
        return size * 1.0 / array.length;
    }


    public int get(int key) {
         // write code here
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}